package com.yonyou.pmclouds.productactive.process;

import com.yonyou.pmclouds.basecom.conf.WorkbenchDataSourceProperties;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.ScriptRunner;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;

@Slf4j
public class ScriptProcess {
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            log.error("缺少数据库驱动", e);
        }
    }

    private static final String SQL_ROOT = "sql/workbench/init/";
    private WorkbenchDataSourceProperties properties;

    public ScriptProcess(WorkbenchDataSourceProperties properties) {
        this.properties = properties;
    }

    public void executeScript(String pkTenant, String sysId) throws BusinessException {
        try (Connection conn = DriverManager.getConnection(properties.getUrl(), properties.getUsername(), properties.getPassword())) {
            conn.setAutoCommit(false);
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setAutoCommit(false);
            runner.setStopOnError(true);
            // 不需要执行这个脚本，只需要执行一次的
//            Reader reader = new InputStreamReader(new ByteArrayInputStream(this.getString("wb_base_data.sql", pkTenant).getBytes()));
//            runner.runScript(reader);
            try {
                String finalScript = this.getString(SQL_ROOT + "wb_base_data_muity.sql", pkTenant, sysId) + this.getString(SQL_ROOT + "menu.sql", pkTenant, sysId);
                Reader reader = new InputStreamReader(new ByteArrayInputStream(finalScript.getBytes("utf-8")),"utf-8");
                runner.runScript(reader);
            } catch (Throwable e) {
                throw e;
            }
            conn.commit();
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }

    }

    private String getString(String filename, String tenantId, String sysId) throws Exception {
        ClassLoader classLoader = getClass().getClassLoader();
        Reader reader = new InputStreamReader(classLoader.getResourceAsStream(filename), "utf-8");
        BufferedReader bf = new BufferedReader(reader);
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = bf.readLine()) != null) {
            buffer.append(line);
            buffer.append("\n");
        }
        String bu = buffer.toString().replaceAll("\\$\\{SYS-ID\\}", sysId).replaceAll("\\$\\{DB-ID\\}", tenantId);
        return bu;
    }
}
